<?php
define('IN_SCRIPT', 1);
define('HESK_PATH', '../');
define('HESK_NO_ROBOTS', 1);

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/database.inc.php');

$category = $_POST['category'];
$description = $_POST['description'];

$tree_json = stripslashes($_POST['json']);
$tree = json_decode($tree_json);
$root = $tree[0];

hesk_dbConnect();

$stack = array();

$start_node = $root->attr->id;

$cat = $_GET['category'];

/* Get ticket info */
$cat = $_POST['parent'];

$sql = "SELECT * FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "diag_parent_cat` WHERE name = '$cat'";
$result = hesk_dbQuery($sql);

$row = hesk_dbFetchAssoc($result);
$cat_id = $row['id'];

if (isset($_POST['id'])) {
    $id = $_POST['id'];
    
    hesk_dbQuery("DELETE FROM hesk_diag_categories WHERE `id` = $id;");
    hesk_dbQuery("DELETE FROM hesk_diag_nodes WHERE `category_id` = $id;");
    
    hesk_dbQuery("INSERT INTO hesk_diag_categories (id, parent_id, name, description, start_node, tree)
VALUES ('$id', '$cat_id', '$category', '$description', '$start_node', '$tree_json')");
} else {
    hesk_dbQuery("INSERT INTO hesk_diag_categories (id, parent_id, name, description, start_node, tree)
VALUES (NULL, '$cat_id', '$category', '$description', '$start_node', '$tree_json')");
}

$category_id = mysql_insert_id();

array_push($stack, $root);

while (count($stack) > 0) {
    $node = array_pop($stack);

    $token = $node->attr->id;
    $type = 1;
    $content = $node->data;
    $yes_node = null;
    $no_node = null;

    if (property_exists($node, 'children')) {
        foreach ($node->children as $child) {
            $type = 0;

            if ($child->attr->class == 'yes_node') {
                $yes_node = $child->attr->id;
            } else if ($child->attr->class == 'no_node') {
                $no_node = $child->attr->id;
            }

            array_push($stack, $child);
        }
    }

    if ($type == 0) {
        hesk_dbQuery("INSERT INTO hesk_diag_nodes (id, category_id, token, type, content, yes_node, no_node) VALUES (NULL, '$category_id', '$token', '$type', '$content', '$yes_node', '$no_node');");
    } else {
        hesk_dbQuery("INSERT INTO hesk_diag_nodes (id, category_id, token, type, content, yes_node, no_node) VALUES (NULL, '$category_id', '$token', '$type', '$content', NULL, NULL);");
    }
}

hesk_dbClose();

echo 'Success';